<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32*32.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16*16.ico?v=6.3.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="问题描述 同事在生产环境中使用Docker去部署ELK日志搜集系统，过程中没有将容器与数据卷挂载。于是持久化的数据都落在了/var/lib/docker/overlay2中。由于服务器需要清理服务器磁盘空间，所以要想无差错清理数据卷中的数据，需要对Docker的文件系统和存储驱动做了解和熟悉。 文件系统OverlayFS OverlayFS是一种和AUFS很类似的文件系统，与AUFS相比，O">
<meta name="keywords" content="Docker,Linux">
<meta property="og:type" content="article">
<meta property="og:title" content="Docker容器占用磁盘内存过大的问题排查">
<meta property="og:url" content="https://gitee.com/hhbbz/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/index.html">
<meta property="og:site_name" content="hhbbz-Blog">
<meta property="og:description" content="问题描述 同事在生产环境中使用Docker去部署ELK日志搜集系统，过程中没有将容器与数据卷挂载。于是持久化的数据都落在了/var/lib/docker/overlay2中。由于服务器需要清理服务器磁盘空间，所以要想无差错清理数据卷中的数据，需要对Docker的文件系统和存储驱动做了解和熟悉。 文件系统OverlayFS OverlayFS是一种和AUFS很类似的文件系统，与AUFS相比，O">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://gitee.com/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/overlay_constructs.jpg">
<meta property="og:updated_time" content="2018-03-29T14:13:52.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Docker容器占用磁盘内存过大的问题排查">
<meta name="twitter:description" content="问题描述 同事在生产环境中使用Docker去部署ELK日志搜集系统，过程中没有将容器与数据卷挂载。于是持久化的数据都落在了/var/lib/docker/overlay2中。由于服务器需要清理服务器磁盘空间，所以要想无差错清理数据卷中的数据，需要对Docker的文件系统和存储驱动做了解和熟悉。 文件系统OverlayFS OverlayFS是一种和AUFS很类似的文件系统，与AUFS相比，O">
<meta name="twitter:image" content="https://gitee.com/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/overlay_constructs.jpg">






  <link rel="canonical" href="https://gitee.com/hhbbz/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Docker容器占用磁盘内存过大的问题排查 | hhbbz-Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">hhbbz-Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">hhbbz</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/blog/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/hhbbz/blog/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="hhbbz">
      <meta itemprop="description" content="摘抄和记录的地方">
      <meta itemprop="image" content="/blog/images/TOM.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hhbbz-Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Docker容器占用磁盘内存过大的问题排查
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-03-28 20:28:01" itemprop="dateCreated datePublished" datetime="2018-03-28T20:28:01+08:00">2018-03-28</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-03-29 22:13:52" itemprop="dateModified" datetime="2018-03-29T22:13:52+08:00">2018-03-29</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/后端/" itemprop="url" rel="index"><span itemprop="name">后端</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/后端/运维/" itemprop="url" rel="index"><span itemprop="name">运维</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1>问题描述</h1>
<p>同事在生产环境中使用Docker去部署ELK日志搜集系统，过程中没有将容器与数据卷挂载。于是持久化的数据都落在了/var/lib/docker/overlay2中。由于服务器需要清理服务器磁盘空间，所以要想无差错清理数据卷中的数据，需要对Docker的文件系统和存储驱动做了解和熟悉。</p>
<h2>文件系统OverlayFS</h2>
<p>OverlayFS是一种和AUFS很类似的文件系统，与AUFS相比，OverlayFS有以下特性：
　　　1) 更简单地设计；
　　　2) 从3.18开始，就进入了Linux内核主线；
　　　3) 可能更快一些。
　　因此，OverlayFS在Docker社区关注度提高很快，被很多人认为是AUFS的继承者。就像宣称的一样，OverlayFS还很年轻。所以，在生成环境使用它时，还是需要更加当心。
&lt;!-- more --&gt;
　　Docker的overlay存储驱动利用了很多OverlayFS特性来构建和管理镜像与容器的磁盘结构。
　　自从Docker1.12起，Docker也支持overlay2存储驱动，相比于overlay来说，overlay2在inode优化上更加高效。但overlay2驱动只兼容Linux kernel4.0以上的版本。</p>
<p><strong><code>注意：自从OverlayFS加入kernel主线后，它在kernel模块中的名称就被从overlayfs改为overlay了。但是为了在本文中区别，我们使用OverlayFS代表整个文件系统，而overlay/overlay2表示Docker的存储驱动。</code></strong></p>
<h2>存储驱动overlay和overlay2</h2>
<h3>OverlayFS（overlay）的镜像分层与共享</h3>
<p>OverlayFS使用两个目录，把一个目录置放于另一个之上，并且对外提供单个统一的视角。这两个目录通常被称作层，这个分层的技术被称作union mount。术语上，下层的目录叫做lowerdir，上层的叫做upperdir。对外展示的统一视图称作merged。
　　如下图所示，Overlay在主机上用到2个目录，这2个目录被看成是overlay的层。 upperdir为容器层、lowerdir为镜像层使用联合挂载技术将它们挂载在同一目录(merged)下，提供统一视图。
<img src="/blog/2018/03/28/Docker容器占用磁盘内存过大的问题排查/overlay_constructs.jpg" title="图片">
　　注意镜像层和容器层是如何处理相同的文件的：容器层（upperdir）的文件是显性的，会隐藏镜像层（lowerdir）相同文件的存在。容器映射（merged）显示出统一的视图。
　　overlay驱动只能工作在两层之上。也就是说多层镜像不能用多层OverlayFS实现。替代的，每个镜像层在/var/lib/docker/overlay中用自己的目录来实现，使用硬链接这种有效利用空间的方法，来引用底层分享的数据。注意：Docker1.10之后，镜像层ID和/var/lib/docker中的目录名不再一一对应。
　　创建一个容器，overlay驱动联合镜像层和一个新目录给容器。镜像顶层是overlay中的只读lowerdir，容器的新目录是可写的upperdir。</p>
<h4>overlay中镜像和容器的磁盘结构</h4>
<p>下面的docker pull命令展示了Docker host下载一个由5层组成的镜像。</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> docker pull ubuntu</span><br><span class="line"></span><br><span class="line">Using default tag: latest</span><br><span class="line">latest: Pulling from library/ubuntu</span><br><span class="line">c62795f78da9: Pull complete</span><br><span class="line">d4fceeeb758e: Pull complete</span><br><span class="line">5c9125a401ae: Pull complete</span><br><span class="line">0062f774e994: Pull complete</span><br><span class="line">6b33fd031fac: Pull complete</span><br><span class="line">Digest: sha256:c2bbf50d276508d73dd865cda7b4ee9b5243f2648647d21e3a471dd3cc4209a0</span><br><span class="line">Status: Downloaded newer image for ubuntu:latests</span><br></pre></td></tr></table></figure></p>
<p>此时，在路径/var/lib/docker/overlay/下，每个镜像层都有一个对应的目录，包含了该层镜像的内容，通过tree命令发现，每个镜像层下只包含一个root目录。 (因为docker1.10开始，使用基于内容的寻址，因此目录名和镜像层的id不一致)。</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> /home/hhbbz# tree -L 2 /var/lib/docker/overlay/</span><br><span class="line"></span><br><span class="line">/var/lib/docker/overlay/</span><br><span class="line">├── 3279a41fd358cdda798d99cc2da0425b4836a489083ae9db4aedc834f426915a</span><br><span class="line">│   └── root</span><br><span class="line">├── 33629fe3999e692ecbeb340f855a2d05ddf4e173ea915041be217e1c9cc8a48f</span><br><span class="line">│   └── root</span><br><span class="line">├── 6ab876fcc7ad584dd1eebae0d9304abb22561012f6adb87828f57906d799c33b</span><br><span class="line">│   └── root</span><br><span class="line">├── 77806a4b8257cd5508a1131d4d47c2d4b4d51703a1cc0dd8daddf0e86a68d492</span><br><span class="line">│   └── root</span><br><span class="line">└── ed271f2159e3c9de18ede980e4e2ecb0ef39b96927d446ba93deab0b6ff1a8e3</span><br><span class="line">    └── root</span><br></pre></td></tr></table></figure></p>
<p>每一层都包含了&quot;该层独有的文件&quot;以及&quot;和其低层共享的数据的硬连接&quot;，如</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> ls -i /var/lib/docker/overlay/3279a41fd358cdda798d99cc2da0425b4836a489083ae9db4aedc834f426915a/root/bin/ls</span><br><span class="line"></span><br><span class="line">405241 /var/lib/docker/overlay/3279a41fd358cdda798d99cc2da0425b4836a489083ae9db4aedc834f426915a/root/bin/ls</span><br><span class="line"></span><br><span class="line"><span class="meta">$</span> /home/hhbbz# ls -i /var/lib/docker/overlay/33629fe3999e692ecbeb340f855a2d05ddf4e173ea915041be217e1c9cc8a48f/root/bin/ls</span><br><span class="line"></span><br><span class="line">405241 /var/lib/docker/overlay/33629fe3999e692ecbeb340f855a2d05ddf4e173ea915041be217e1c9cc8a48f/root/bin/ls</span><br></pre></td></tr></table></figure></p>
<p>每一层都使用一个硬链接来指向实际ls命令的inode号(405241)。使用刚刚拉取的ubuntu镜像创建一个容器，用docker ps命令查看：</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> /home/hhbbz# docker ps</span><br><span class="line"></span><br><span class="line">CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES</span><br><span class="line">8963ffb422fa        ubuntu              "/bin/bash"         32 minutes ago      Up 52 seconds                           container_1</span><br></pre></td></tr></table></figure></p>
<p>创建容器时，实际上是在已有的镜像层上创建了一层容器层，容器层在路径/var/lib/docker/overlay下也存在对应的目录：</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">$</span> /home/hhbbz# ls /var/lib/docker/overlay/</span><br><span class="line"></span><br><span class="line">3279a41fd358cdda798d99cc2da0425b4836a489083ae9db4aedc834f426915a</span><br><span class="line">33629fe3999e692ecbeb340f855a2d05ddf4e173ea915041be217e1c9cc8a48f</span><br><span class="line">6ab876fcc7ad584dd1eebae0d9304abb22561012f6adb87828f57906d799c33b</span><br><span class="line">6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d       //创建容器后新增的目录</span><br><span class="line">6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d-init  //创建容器后新增的目录</span><br><span class="line">77806a4b8257cd5508a1131d4d47c2d4b4d51703a1cc0dd8daddf0e86a68d492</span><br><span class="line">ed271f2159e3c9de18ede980e4e2ecb0ef39b96927d446ba93deab0b6ff1a8e3</span><br></pre></td></tr></table></figure></p>
<p>“6abc47……”和“6abc47…..-init”为创建容器后新增的目录。查看这两个目录的内容:</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> /home/hhbbz# tree -L 3 /var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d*/</span><br><span class="line"></span><br><span class="line">/var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d/</span><br><span class="line">├── lower-id</span><br><span class="line">├── merged</span><br><span class="line">├── upper</span><br><span class="line">│   ├── dev</span><br><span class="line">│   │   └── console</span><br><span class="line">│   ├── etc</span><br><span class="line">│   │   ├── hostname</span><br><span class="line">│   │   ├── hosts</span><br><span class="line">│   │   ├── mtab -&gt; /proc/mounts</span><br><span class="line">│   │   └── resolv.conf</span><br><span class="line">│   └── root</span><br><span class="line">└── work</span><br><span class="line">    └── work</span><br><span class="line"></span><br><span class="line">/var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d-init/</span><br><span class="line">├── lower-id</span><br><span class="line">├── merged</span><br><span class="line">├── upper</span><br><span class="line">│   ├── dev</span><br><span class="line">│   │   └── console</span><br><span class="line">│   └── etc</span><br><span class="line">│       ├── hostname</span><br><span class="line">│       ├── hosts</span><br><span class="line">│       ├── mtab -&gt; /proc/mounts</span><br><span class="line">│       └── resolv.conf</span><br><span class="line">└── work</span><br><span class="line">    └── work</span><br></pre></td></tr></table></figure></p>
<p>“6abc47……”为读写层，“6abc47…..-init”为初始层。 初始层中大多是初始化容器环境时，与容器相关的环境信息， 如容器主机名，主机host信息以及域名服务文件等。所有对容器做出的改变都记录在读写层。</p>
<p>文件lower-id用来索引该容器使用的镜像层，upper目录包含了容器层的内容，每当启动一个容器时，会将lower-id指向的镜像层目录以及upper目录联合挂载到merged目录，因此，容器内的视角就是merged目录下的内容。而work目录则是用来完成如copy-on_write的操作。 看看容器使用到了哪一层镜像层：</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> /home/hhbbz# cat /var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d/lower-id</span><br><span class="line"></span><br><span class="line">ed271f2159e3c9de18ede980e4e2ecb0ef39b96927d446ba93deab0b6ff1a8e3</span><br><span class="line"></span><br><span class="line"><span class="meta">$</span> /home/hhbbz# cat /var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d-init/lower-id</span><br><span class="line"></span><br><span class="line">ed271f2159e3c9de18ede980e4e2ecb0ef39b96927d446ba93deab0b6ff1a8e3</span><br></pre></td></tr></table></figure></p>
<p>在刚才创建的容器中创建一个文件：</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">root@8963ffb422fa:/# touch file</span><br><span class="line"></span><br><span class="line">root@8963ffb422fa:/# echo "hello world" &gt; file</span><br><span class="line"></span><br><span class="line">root@8963ffb422fa:/# ls</span><br><span class="line">bin   dev  file  lib    media  opt   root  sbin  sys  usr</span><br><span class="line">boot  etc  home  lib64  mnt    proc  run   srv   tmp  var</span><br></pre></td></tr></table></figure></p>
<p>此时再观察“6abc47……”目录(读写层)：</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> /home/hhbbz# tree -L 3 /var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d/  </span><br><span class="line"></span><br><span class="line">/var/lib/docker/overlay/6abc47fcf668b6820a2a9a8b0d0c6150f9df61ab5a323783630fac3fd282144d/</span><br><span class="line">├── lower-id</span><br><span class="line">├── merged</span><br><span class="line">├── upper</span><br><span class="line">│   ├── dev</span><br><span class="line">│   │   └── console</span><br><span class="line">│   ├── etc</span><br><span class="line">│   │   ├── hostname</span><br><span class="line">│   │   ├── hosts</span><br><span class="line">│   │   ├── mtab -&gt; /proc/mounts</span><br><span class="line">│   │   └── resolv.conf</span><br><span class="line">│   ├── file</span><br><span class="line">│   └── root</span><br><span class="line">└── work</span><br><span class="line">    └── work</span><br></pre></td></tr></table></figure></p>
<p>发现upper目录下多出了一个file文件，就是刚才在容器中创建的文件。</p>
<h3>OverlayFS（overlay2）的镜像分层与共享</h3>
<p>和overlay为了实现“两个目录反映多层镜像“而使用硬链接不同，overlay2驱动天生支持多层。(最多128)</p>
<p>因此，overlay2在使用docker层相关的命令时，能提供更好的性能(如：docker build、docker commit)。而且overlay2消耗的inode节点更少。</p>
<h4>overlay2中镜像和容器的磁盘结构</h4>
<p>docker pull ubuntu拉取完一个5层的Ubuntu镜像后，/var/lib/docker/overlay2下可以看到6个目录:</p>
<p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> /home/hhbbz# tree -L 2 /var/lib/docker/overlay2</span><br><span class="line"></span><br><span class="line">/var/lib/docker/overlay2</span><br><span class="line">├── 1d18eac18e483e5af46d52673e254cb89996041d91356c6dd1f0ac1518ba130a</span><br><span class="line">│   ├── diff</span><br><span class="line">│   └── link   //文件</span><br><span class="line">├── 28702e0cca9ff9a3245ce7e61326d098788e855ea599bf160465f537756a56a6</span><br><span class="line">│   ├── diff</span><br><span class="line">│   ├── link   //文件</span><br><span class="line">│   ├── lower   //文件</span><br><span class="line">│   ├── merged</span><br><span class="line">│   └── work</span><br><span class="line">├── 299397034eb96f22d544bf544c9ef993fa32571f466bd8a881aec0fc5a94a8df</span><br><span class="line">│   ├── diff</span><br><span class="line">│   ├── link   //文件</span><br><span class="line">│   ├── lower   //文件</span><br><span class="line">│   ├── merged</span><br><span class="line">│   └── work</span><br><span class="line">├── 8c0de7df4581df4787b08a28356cc8d7ba7b420c70dc36cc0615afdafb6ee15a</span><br><span class="line">│   ├── diff</span><br><span class="line">│   ├── link   //文件</span><br><span class="line">│   ├── lower   //文件</span><br><span class="line">│   ├── merged</span><br><span class="line">│   └── work</span><br><span class="line">├── f21a47541026214e519fccdf8b838ac2c4e11a1a2dd6a5febc061381a1972ad7</span><br><span class="line">│   ├── diff</span><br><span class="line">│   ├── link   //文件</span><br><span class="line">│   ├── lower   //文件</span><br><span class="line">│   ├── merged</span><br><span class="line">│   └── work</span><br><span class="line">└── l</span><br><span class="line">    ├── 5DJFQNGXSA5CVOC6NA6HPUCXXB -&gt; ../299397034eb96f22d544bf544c9ef993fa32571f466bd8a881aec0fc5a94a8df/diff</span><br><span class="line">    ├── EGQNS3O24ONBL5BJSGNTX4NP6E -&gt; ../1d18eac18e483e5af46d52673e254cb89996041d91356c6dd1f0ac1518ba130a/diff</span><br><span class="line">    ├── JWB63ZJDZOTK5N22OMR5BKUVMG -&gt; ../8c0de7df4581df4787b08a28356cc8d7ba7b420c70dc36cc0615afdafb6ee15a/diff</span><br><span class="line">    ├── UZHRLLTPQMODQQYBLN6NOT6N2K -&gt; ../28702e0cca9ff9a3245ce7e61326d098788e855ea599bf160465f537756a56a6/diff</span><br><span class="line">    └── X76VPZDDKIW3GLWBFUHKDFBEPE -&gt; ../f21a47541026214e519fccdf8b838ac2c4e11a1a2dd6a5febc061381a1972ad7/diff</span><br><span class="line"></span><br><span class="line">24 directories, 9 files</span><br></pre></td></tr></table></figure></p>
<p>”l“目录包含一些符号链接作为缩短的层标识符. 这些缩短的标识符用来避免挂载时超出页面大小的限制。
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$ /home/hhbbz# ls -l /var/lib/docker/overlay2/l/</span><br><span class="line">    </span><br><span class="line">总用量 20</span><br><span class="line">lrwxrwxrwx 1 root root 72  4月 20 17:31 5DJFQNGXSA5CVOC6NA6HPUCXXB -&gt; ../299397034eb96f22d544bf544c9ef993fa32571f466bd8a881aec0fc5a94a8df/diff</span><br><span class="line">lrwxrwxrwx 1 root root 72  4月 20 17:31 EGQNS3O24ONBL5BJSGNTX4NP6E -&gt; ../1d18eac18e483e5af46d52673e254cb89996041d91356c6dd1f0ac1518ba130a/diff</span><br><span class="line">lrwxrwxrwx 1 root root 72  4月 20 17:31 JWB63ZJDZOTK5N22OMR5BKUVMG -&gt; ../8c0de7df4581df4787b08a28356cc8d7ba7b420c70dc36cc0615afdafb6ee15a/diff</span><br><span class="line">lrwxrwxrwx 1 root root 72  4月 20 17:31 UZHRLLTPQMODQQYBLN6NOT6N2K -&gt; ../28702e0cca9ff9a3245ce7e61326d098788e855ea599bf160465f537756a56a6/diff</span><br><span class="line">lrwxrwxrwx 1 root root 72  4月 20 17:31 X76VPZDDKIW3GLWBFUHKDFBEPE -&gt; ../f21a47541026214e519fccdf8b838ac2c4e11a1a2dd6a5febc061381a1972ad7/diff</span><br></pre></td></tr></table></figure></p>
<p>最底层包含”link”文件(不包含lower文件，因为是最底层)，在上面的结果中“1d8e….”为最底层。 这个文件记录着作为标识符的更短的符号链接的名字、最底层还有一个”diff”目录(包含实际内容)。
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$ /home/hhbbz# cat /var/lib/docker/overlay2/1d18eac18e483e5af46d52673e254cb89996041d91356c6dd1f0ac1518ba130a/link </span><br><span class="line">    </span><br><span class="line">EGQNS3O24ONBL5BJSGNTX4NP6E</span><br><span class="line">    </span><br><span class="line">root@hhbbz-MS-7823:/home/hhbbz# ls /var/lib/docker/overlay2/1d18eac18e483e5af46d52673e254cb89996041d91356c6dd1f0ac1518ba130a/diff/</span><br><span class="line">    </span><br><span class="line">bin   dev  home  lib64  mnt  proc  run   srv  tmp  var</span><br><span class="line">boot  etc  lib   media  opt  root  sbin  sys  usr</span><br></pre></td></tr></table></figure></p>
<p>从第二层开始，每层镜像层包含”lower“文件，根据这个文件可以索引构建出整个镜像的层次结构。 ”diff“文件(层的内容)。还包含”merged“和”work”目录，用途和overlay一样。
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">$ /home/hhbbz# cat /var/lib/docker/overlay2/28702e0cca9ff9a3245ce7e61326d098788e855ea599bf160465f537756a56a6/link </span><br><span class="line">    </span><br><span class="line">UZHRLLTPQMODQQYBLN6NOT6N2K</span><br><span class="line">    </span><br><span class="line">$ /home/hhbbz# ls /var/lib/docker/overlay2/28702e0cca9ff9a3245ce7e61326d098788e855ea599bf160465f537756a56a6/diff/</span><br><span class="line">    </span><br><span class="line">etc  sbin  usr  var</span><br><span class="line">    </span><br><span class="line">$ /home/hhbbz# cat /var/lib/docker/overlay2/28702e0cca9ff9a3245ce7e61326d098788e855ea599bf160465f537756a56a6/lower</span><br><span class="line">    </span><br><span class="line">l/EGQNS3O24ONBL5BJSGNTX4NP6E</span><br></pre></td></tr></table></figure></p>
<p>再来看看容器层，容器层的文件构成和镜像层类似(这点和overlay不同)，使用刚刚拉取的ubuntu镜像创建一个容器，/var/lib/docker/overlay2目录下新增2个目录：
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">├── 2558ed8dd7051c1e78ea980590a228100ec3d299c01b35e9b7fa503723593d19</span><br><span class="line">│   ├── diff</span><br><span class="line">│   ├── link</span><br><span class="line">│   ├── lower</span><br><span class="line">│   ├── merged</span><br><span class="line">│   └── work</span><br><span class="line">├── 2558ed8dd7051c1e78ea980590a228100ec3d299c01b35e9b7fa503723593d19-init</span><br><span class="line">│   ├── diff</span><br><span class="line">│   ├── link</span><br><span class="line">│   ├── lower</span><br><span class="line">│   ├── merged</span><br><span class="line">│   └── work</span><br><span class="line">└── l</span><br><span class="line">    ├── 7H7MUMX4IOAVLIJ2YPLR5MZOO5 -&gt; ../2558ed8dd7051c1e78ea980590a228100ec3d299c01b35e9b7fa503723593d19-init/diff</span><br><span class="line">    ├── EBSBKJBLA2WYBHTMHKSMCEEWNP -&gt; ../2558ed8dd7051c1e78ea980590a228100ec3d299c01b35e9b7fa503723593d19/diff</span><br><span class="line"></span><br><span class="line">$ /home/hhbbz# cat /var/lib/docker/overlay2/2558ed8dd7051c1e78ea980590a228100ec3d299c01b35e9b7fa503723593d19/lower </span><br><span class="line">    </span><br><span class="line">l/7H7MUMX4IOAVLIJ2YPLR5MZOO5:l/5DJFQNGXSA5CVOC6NA6HPUCXXB:l/JWB63ZJDZOTK5N22OMR5BKUVMG:l/X76VPZDDKIW3GLWBFUHKDFBEPE:l/UZHRLLTPQMODQQYBLN6NOT6N2K:l/EGQNS3O24ONBL5BJSGNTX4NP6E</span><br></pre></td></tr></table></figure></p>
<h3>容器的读写</h3>
<p>对于读，考虑下列3种场景：</p>
<ul>
<li>读的文件不在容器层：如果读的文件不在容器层，则从镜像层进行读</li>
<li>读的文件只存在在容器层：直接从容器层读</li>
<li>读的文件在容器层和镜像层：读容器层中的文件，因为容器层隐藏了镜像层同名的文件</li>
</ul>
<p>对于写，考虑下列场景：</p>
<ul>
<li>写的文件不在容器层，在镜像层：由于文件不在容器层，因此overlay/overlay2存储驱动使用copy_up操作从镜像层拷贝文件到容器层，然后将写入的内容写入到文件新的拷贝中。</li>
<li>删除文件和目录：删除镜像层的文件，会在容器层创建一个whiteout文件来隐藏它；删除镜像层的目录，会创建opaque目录，它和whiteout文件有相同的效果</li>
<li>重命名目录：对一个目录调用rename(2)仅仅在资源和目的地路径都在顶层时才被允许，否则返回EXDEV。</li>
</ul>
<h2>问题解决</h2>
<p>最后通过在/var/lib/docker/overlay2目录下执行
<code>du -sh *</code>
找到占用磁盘空间最大的几个文件夹，进行审查清理。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/blog/images/wechat.png" alt="hhbbz 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Docker/" rel="tag"># Docker</a>
          
            <a href="/blog/tags/Linux/" rel="tag"># Linux</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/03/26/SpringBoot+RocketMQ做分布式消息队列/" rel="next" title="SpringBoot+RocketMQ做分布式消息队列">
                <i class="fa fa-chevron-left"></i> SpringBoot+RocketMQ做分布式消息队列
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/04/16/Spring-Cloud微服务初步架构设计/" rel="prev" title="Spring Cloud微服务初步架构设计">
                Spring Cloud微服务初步架构设计 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/TOM.jpg"
                alt="hhbbz" />
            
              <p class="site-author-name" itemprop="name">hhbbz</p>
              <p class="site-description motion-element" itemprop="description">摘抄和记录的地方</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/hhbbz" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:hhbbz@outlook.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://coding.net/u/hhbbz" target="_blank" title="Coding" rel="external nofollow"><i class="fa fa-fw fa-github-alt"></i>Coding</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hhbbz</span>

  

  
</div>


  



  <div class="powered-by">Power By HEXO</div>








        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'DcsJEQ0LBt3NnDvMcJ8cJwry-gzGzoHsz',
        appKey: 'HSCBfA4q42WQQovBbS25Yp3A',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  

  


  
  

  

  

  

  

  

</body>
</html>
